package com.bwda.dsrs.systemservice.controller;


import com.bwda.dsrs.base.util.CopyUtil;
import com.bwda.dsrs.systemservice.domain.Constants;
import com.bwda.dsrs.systemservice.domain.condition.user.UserCondition;
import com.bwda.dsrs.systemservice.domain.condition.usersecurity.UserSecurityCondition;
import com.bwda.dsrs.systemservice.domain.exception.SystemServiceException;
import com.bwda.dsrs.systemservice.domain.form.login.LoginForm;
import com.bwda.dsrs.systemservice.domain.po.user.UserPo;
import com.bwda.dsrs.systemservice.domain.po.usersecurity.UserSecurityPo;
import com.bwda.dsrs.systemservice.service.UserSecurityService;
import com.bwda.dsrs.systemservice.service.UserService;
import com.bwda.dsrs.systemservice.utils.RequestUtil;
import com.bwda.dsrs.systemservice.utils.ShiroKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yanyuemei
 * @date 2019/4/3
 */
@RestController
@RequestMapping("/s")
@Api(value = "/s", tags = "用户等级")
public class SsoController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserSecurityService userSecurityService;

    private static final String ERROR_CODE = "0";

    private static final String CODE_FIELD = "code";

    private static final int LOGIN_FAIL_TIME = 5;

    @ApiOperation(value = "登录", notes = "登录", httpMethod = "GET")
    @RequestMapping(value = "/ssoLogin", method = {RequestMethod.GET, RequestMethod.POST})
    public void ssoLogin(HttpServletRequest request, HttpServletResponse response) throws SystemServiceException, Exception {
        //TODO 错误页面待确认
        String strError = "/base_Action!jump.do?jumpPath=error";
        String strSuccess = "";
        //用户code
        String userCode = RequestUtil.getString(request, "arg1");
        //用户密码
        String password = RequestUtil.getString(request, "arg2");
        UserPo user = userService.queryUserByUserCode(userCode);
        if (user == null) {
            response.sendRedirect(strError);
        } else {
            if (Constants.USER_FREEZE == user.getUserState()) {
                response.sendRedirect(strError);
            } else if (Constants.USER_LOCK == user.getUserState()) {
                response.sendRedirect(strError);
            } else {
                UserSecurityCondition userSecurityCondition = new UserSecurityCondition();
                userSecurityCondition.setUserCode(user.getUserCode());
                UserSecurityPo userSecurityPo = userSecurityService.query(userSecurityCondition);
                //用户安全策略不存在，则生成用户策略
                if (userSecurityPo == null) {
                    userSecurityPo = new UserSecurityPo();
                    userSecurityPo.setUserCode(user.getUserCode());
                    userSecurityPo.setPasswordRuleId(Constants.ZERO_INT);
                    userSecurityPo.setEffTime(new Date());
                    userSecurityPo.setCreateTime(new Date());
                    userSecurityService.insert(userSecurityPo);
                }
                Map<String, String> resultStr = this.authUserIdentity(password, user, userSecurityPo);
                if (!ERROR_CODE.equals(resultStr.get(CODE_FIELD))) {
                    response.sendRedirect(strError);
                } else {
                    String token = resultStr.get("msg");
                    //保存用户信息
                    response.setHeader("Authorization", token);
                }
            }
        }
        response.sendRedirect(strSuccess);
    }

    /**
     * 验证用户信息是否正确
     *
     * @param user
     * @param userSecurityPo
     * @return
     */
    private Map<String, String> authUserIdentity(String password, UserPo user, UserSecurityPo userSecurityPo) {
        Map<String, String> result = new HashMap<String, String>(16);
        String userCode = user.getUserCode();
        int loginFailTime = userSecurityPo.getLoginFailCount() == null ? 0 : userSecurityPo.getLoginFailCount();
        if (loginFailTime > LOGIN_FAIL_TIME) {
            result.put("code", "1");
            result.put("msg", "用户登录失败次数已超出限制");
        } else {
            String salt = "";
//            String encodedPassword = ShiroKit.md5(password, userCode + salt);
            String encodedPassword = "";
            if (user.getPassword().equals(encodedPassword)) {
                //用户名密码校验正确，则更新安全策略登录成功次数
                userSecurityPo.setLoginSuceeCount((userSecurityPo.getLoginSuceeCount() == null ? 0 : userSecurityPo.getLoginSuceeCount()) + 1);
                userSecurityService.update(userSecurityPo);
                result.put("code", "0");
            } else {
                //用户名密码校验不正确，则更新安全策略登录失败次数
                userSecurityPo.setLoginFailCount((userSecurityPo.getLoginFailCount() == null ? 0 : userSecurityPo.getLoginFailCount()) + 1);
                userSecurityService.update(userSecurityPo);
                result.put("code", "1");
                result.put("msg", "用户名或密码不正确");
            }
        }
        return result;
    }

    /**
     * MenuQueryForm转换为MenuCondition
     *
     * @param form
     * @return
     */
    private UserCondition getConditionByQueryForm(LoginForm form) {
        UserCondition condition = CopyUtil.transfer(form, UserCondition.class);
        return condition;
    }

}
